<template>
  <BaseLayout>
    <template #content>
      <div class="carousel-list">
        <div class="carousel-list-header">
          <el-button
            type="primary"
            @click="handleAddDialogOpen"
          >
            新增轮播图
          </el-button>
        </div>

        <div class="carousel-list-body">
          <el-table
            border
            :data="tableList"
            :stripe="true"
            :header-cell-style="() => ({ background: '#F8F8F8' })"
          >
            <el-table-column
              label="序号"
              type="index"
              width="100"
              align="center"
            />

            <el-table-column
              prop="title"
              label="标题"
              align="center"
              show-overflow-tooltip
            />

            <el-table-column
              prop="description"
              label="描述"
              align="center"
              show-overflow-tooltip
            />

            <el-table-column
              prop="sorted"
              label="排序"
              align="center"
              show-overflow-tooltip
            />

            <el-table-column
              label="操作"
              align="center"
              width="150"
            >
              <template #default="scope">
                <el-button
                  size="small"
                  @click="handleEditDialogOpen(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDeleteCarousel(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <el-dialog
        v-model="formDialogVisible"
        :title="isEdit ? '编辑轮播图' : '新增轮播图'"
        width="50%"
        :before-close="handleDialogClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        align-center
        append-to-body
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="50px"
          label-position="left"
        >
          <el-form-item
            label="标题"
            prop="title"
          >
            <el-input
              v-model="form.title"
              placeholder="请输入标题"
            />
          </el-form-item>

          <el-form-item
            label="描述"
            prop="description"
          >
            <el-input
              type="textarea"
              v-model="form.description"
              placeholder="请输入描述"
              :autosize="{ minRows: 2, maxRows: 5 }"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item
            label="排序"
            prop="sorted"
          >
            <el-input-number
              v-model="form.sorted"
              :min="1"
              :max="5"
            />
          </el-form-item>

          <el-form-item
            label="视频"
            prop="videoId"
          >
            <el-button @click="handleVideoSelectDialogOpen(form.videoId)">
              {{ form.videoId ? '已选择' : '选择视频' }}
            </el-button>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="handleDialogClose">取消</el-button>

          <el-button
            type="primary"
            @click="handleSubmit"
          >
            确定
          </el-button>
        </template>
      </el-dialog>

      <el-dialog
        v-model="videoSelectDialogVisible"
        title="视频选择"
        width="70%"
        :before-close="handleVideoSelectDialogClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        align-center
        append-to-body
      >
        <el-table :data="videoTableList">
          <el-table-column
            prop="title"
            label="标题"
            align="center"
            show-overflow-tooltip
          />

          <el-table-column
            prop="nickname"
            label="作者"
            align="center"
            show-overflow-tooltip
          />

          <el-table-column
            prop="viewCount"
            label="播放量"
            :formatter="numberFormat"
            align="center"
            show-overflow-tooltip
          />

          <el-table-column
            prop="publishTime"
            label="创建时间"
            :formatter="timeFormat"
            align="center"
            show-overflow-tooltip
          />

          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleVideoSelect(scope.row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <Pagination
          style="margin-top: 20px"
          v-show="videoTableList.length > 0"
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getVideoList"
        />
      </el-dialog>
    </template>
  </BaseLayout>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { deleteCarousel, getCarouselList, saveCarousel } from '@/api/carousel'
import { ElMessage } from 'element-plus'
import { showDangerMessageBox } from '@/utils/messageUtil'
import { getVideoPage } from '@/api/video'
import Pagination from '@/components/Pagination/index.vue'
import dayjs from 'dayjs'

const tableList = ref<any[]>([])

onMounted(async () => {
  tableList.value = await getCarouselList()
})

/**
 * 删除轮播图
 */
const handleDeleteCarousel = async row => {
  showDangerMessageBox('警告', '确定要删除吗？', async () => {
    try {
      await deleteCarousel(row.id)
      ElMessage.success('删除成功')
      tableList.value = await getCarouselList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// ========== 新增/编辑 ==========

const form = reactive({
  id: '',
  title: '',
  description: '',
  videoId: '',
  sorted: 0
})

const formRef = ref()
const rules = reactive({
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: 'blur'
    }
  ],
  videoId: [
    {
      required: true,
      message: '请选择视频',
      trigger: 'blur'
    }
  ],
  sorted: [
    {
      required: true,
      message: '请输入排序',
      trigger: 'blur'
    }
  ]
})

const formDialogVisible = ref(false)
const isEdit = ref(false)

/**
 * 打开新增对话框
 */
const handleAddDialogOpen = () => {
  isEdit.value = false
  formDialogVisible.value = true
}

/**
 * 打开编辑对话框
 */
const handleEditDialogOpen = row => {
  Object.assign(form, row)
  isEdit.value = true
  formDialogVisible.value = true
}

/**
 * 提交表单
 */
const handleSubmit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        if (!isEdit.value && tableList.value.length >= 5) {
          ElMessage.error('最多只能添加 5 个轮播图')
          return
        }
        await saveCarousel(form)
        ElMessage.success('操作成功')
        handleDialogClose()
        tableList.value = await getCarouselList()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

/**
 * 关闭对话框
 */
const handleDialogClose = () => {
  formDialogVisible.value = false
  form.id = ''
  form.title = ''
  form.description = ''
  form.videoId = ''
  form.sorted = 0
  formRef.value.clearValidate()
}

// ========== 视频选择 ==========
const videoSelectDialogVisible = ref(false)
const videoTableList = ref<any[]>([])
const total = ref(0)

const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})

const getVideoList = async () => {
  const res = await getVideoPage(queryParams.value)
  videoTableList.value = res.list
  total.value = res.total
}

const handleVideoSelectDialogOpen = async (videoId: number) => {
  await getVideoList()
  videoSelectDialogVisible.value = true
}

/**
 * 视频选择
 */
const handleVideoSelect = video => {
  if (form.videoId !== video.id && tableList.value.find(item => item.videoId === video.id)) {
    ElMessage.error('该视频已添加，请选择其它视频')
    return
  }

  form.videoId = video.id
  handleVideoSelectDialogClose()
}

const handleVideoSelectDialogClose = () => {
  videoTableList.value = []
  queryParams.value = {
    pageNo: 1,
    pageSize: 10
  }
  videoSelectDialogVisible.value = false
}

const numberFormat = (_row, _col, cellValue) => {
  if (cellValue >= 10000) return (cellValue / 10000).toFixed(1) + 'w'
  if (cellValue >= 1000) return (cellValue / 1000).toFixed(1) + 'k'
  return cellValue
}

const timeFormat = (_row, _col, cellValue) => {
  if (!cellValue) {
    return ''
  }
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm')
}
</script>

<style scoped lang="scss">
.carousel-list-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
</style>
